package com.kj2l2.common.mapper;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.kj2l2.common.controller.Controller;
import com.kj2l2.common.controller.FormController;
import com.kj2l2.common.servlet.DispatcherServlet;

public class SimpleHandlerMapping {
	private HashMap<String,HashMap<String,Controller>> Commands;
	private static SimpleHandlerMapping instance;

	private SimpleHandlerMapping(DispatcherServlet servlet) {
		try{
			Commands=new HashMap<String,HashMap<String,Controller>>();
			DispatcherServlet s=servlet;
			String path=s.getInitParameter("commandsFile");
			String[] st=path.split(",");
			for(String comm:st){
				String key=comm.split("/")[2].split("\\.")[0];
				String aPath=s.getServletContext().getRealPath(comm);
				System.out.println("aPath....."+aPath);
				HashMap<String,Controller> hashmap=new HashMap<String,Controller>();
				FileInputStream fis=new FileInputStream(aPath);
				Properties properties=new Properties();
				properties.load(fis);
				Set<String> set=properties.stringPropertyNames();
				for(String nm : set){
					hashmap.put(nm,(Controller)(Class.forName(properties.getProperty(nm))).newInstance());
				}
				Commands.put(key, hashmap);
			}
		}catch(FileNotFoundException e){
			System.out.println(e.getMessage());
		}catch(IOException ee){
			System.out.println(ee.getMessage());
		}catch(Exception eee){
			System.out.println(eee.getMessage());
		}
	}
	public static SimpleHandlerMapping getInstance(DispatcherServlet servlet) {
		if(instance==null)
			instance=new SimpleHandlerMapping(servlet);
		return instance;
	}

	public Controller getController(HttpServletRequest request) throws Exception {
		String[] cmd = request.getRequestURI().split("/");
		System.out.println("cmd[1]....."+cmd[2]);
		HashMap<String,Controller> hashmap=Commands.get(cmd[2]);
		String ccmd=cmd[3].trim().toLowerCase();
		if(hashmap.containsKey(ccmd))
			return hashmap.get(ccmd);
		else
			return new FormController();

	}
}
